function GlobalFn() {
    var that = this;
    if (!Promise) {
        var script = document.createElement('script');
        script.src = './js/polyfill.min.js';
        document.body.appendChild(script)
    }

    this.getBase64Image = function (img) {
        var canvas = document.createElement("canvas"),
            ctx,
            dataURL;
        canvas.width = img.width;
        canvas.height = img.height;
        ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        dataURL = canvas.toDataURL("image/png");  // 可选其他值 image/jpeg
        return dataURL;
    };
    /*
    * 返回地址全部参数的对象
    * */
    this.getUrlQuery = function () {
        var search = location.search.substr(1),
            arr = search.split('&'),
            obj = {},
            ar;
        arr.forEach(function (item) {
            ar = item.split('=');
            obj[ar[0]] = decodeURIComponent(ar[1]);
        });
        return obj
    };
    /*
    * 消息提示
    * Object options={
    *   isModal:Boolean, 是否显示遮罩
    *   isCancelBtn:Boolean, 是否显示取消按钮
    *   title:String,   标题
    *   text:String   内容
    *   success:Function  点击确认回调
    *   failed:Function 点击取消回调
    * }
    * */
    this.message = function (options) {
        return new Promise(function (resolve, reject) {
            //生产提示消息
            var title = options.title || '温馨提示',
                text = options.text || '',
                cancelBtnClassName = options.isCancelBtn ? "g_messageBtn isCancel" : "g_messageBtn",
                modalClassName = options.isModal ? "g_modal isModal" : "g_modal",
                g_messageContainer = document.createElement('div'),
                g_modal, //遮罩
                g_messageCancelBtn,//取消按钮
                g_messageConfirmBtn; //确认按钮

            g_messageContainer.setAttribute('class', 'g_messageContainer');
            g_messageContainer.innerHTML = "<div id='g_modal' class='" + modalClassName + "'></div>" +
                "<div class='g_messageWarp'>" +
                "<h3 class='g_messageTitle'>" + title + "</h3>" +
                "<div class='g_messageContent'>" + text + "</div>" +
                "<div class='g_messageBtnGroup'>" +
                "</div>" +
                "</div>";
            var old_g_messageContainer = document.getElementsByClassName('g_messageContainer')[0];
            if(old_g_messageContainer){
                document.body.removeChild(old_g_messageContainer)
            }
            document.body.appendChild(g_messageContainer);
            var g_messageBtnGroup = g_messageContainer.getElementsByClassName('g_messageBtnGroup')[0];
            var cancelBtn = document.createElement('div');
            var confirmBtn = document.createElement('div');
            cancelBtn.className = cancelBtnClassName;
            cancelBtn.id = 'g_messageCancelBtn';
            cancelBtn.innerText = '取消';
            confirmBtn.className  = 'g_messageBtn';
            confirmBtn.id =  'g_messageConfirmBtn';
            confirmBtn.innerText = '确认';
            g_messageBtnGroup.appendChild(cancelBtn);
            g_messageBtnGroup.appendChild(confirmBtn);

            //确认
            function confirm() {
                resolve();
                if (!!options['success']) options['success']();
                document.body.removeChild(g_messageContainer)
            }

            //取消
            function cancel() {
                reject();
                if (!!options['failed']) options['failed']();
                document.body.removeChild(g_messageContainer)
            }

            //执行确认
            confirmBtn.onclick = function (e) {
                e.stopPropagation();
                confirm()
            };
            //执行取消
            g_modal = document.getElementById('g_modal');
            g_modal.onclick = function (e) {
                e.stopPropagation();
                cancel()
            };
            if (options['isCancelBtn']) {
                cancelBtn.onclick = function (e) {
                    e.stopPropagation();
                    cancel()
                };
            }
        })
    };

    /*
    * 选择框弹窗选择器
    * Array options 选项数组
    * item = {name:"",...}   name 为必选项，用于显示选项文本
    * */
    this.selectOption = function (options) {
        return new Promise(function (resolve, reject) {
            var g_selectDropdown = document.createElement('div'),
                g_select_mask = document.createElement('div'),
                g_select_content = document.createElement('div'),
                g_select_btnGroup = document.createElement('div'),
                g_selectGroup = document.createElement('div');
            g_selectDropdown.className = 'g_selectDropdown';
            g_select_mask.className = 'g_select_mask';
            g_select_content.className = 'g_select_content';
            g_select_btnGroup.className = 'g_select_btnGroup';
            g_selectGroup.className = 'g_selectGroup';
            g_selectDropdown.appendChild(g_select_mask); // 插入遮罩节点

            var cancelBtn = document.createElement('span'),
                confirm = document.createElement('span');
            cancelBtn.innerText = '取消';
            confirm.innerText = '确认';

            g_select_btnGroup.appendChild(cancelBtn);
            // g_select_btnGroup.appendChild(confirm);
            g_select_content.appendChild(g_select_btnGroup);
            cancelBtn.onclick = function (e) {
                e.preventDefault();
                e.stopPropagation()
                cancel()
            };
            g_select_mask.onclick = function (e) {
                e.preventDefault();
                e.stopPropagation()
                cancel()
            };
            options.forEach(function (item) {
                var li = document.createElement('li');
                li.className = 'g_select_item';
                for (var key in item) {
                    li['options_' + key] = item[key]
                }
                li.innerText = item.name;
                li.onclick = function () {
                    resolve(item);
                    removeDropdown()
                };
                g_selectGroup.appendChild(li)
            });
            g_select_content.appendChild(g_selectGroup);
            g_selectDropdown.appendChild(g_select_content)
            document.body.appendChild(g_selectDropdown)
            document.body.addEventListener('touchmove',that.banEventDefault);
            document.getElementById('warpContainer').style.overflow = 'hidden';
            function removeDropdown() {
                document.getElementById('warpContainer').style.overflow = 'auto';
                document.body.removeEventListener('touchmove',that.banEventDefault);
                g_select_content.className += ' dropDown_line_out';
                g_select_mask.className += ' dropDown_ease_out';
                setTimeout(function () {
                    if(!!document.body.getElementsByClassName('g_selectDropdown')[0]){
                        g_select_mask.style.opacity = '0';
                        g_select_content.style.transform = 'translateY(100%)';
                        g_select_content.style.animationDirection = '0';
                        document.body.removeChild(g_selectDropdown);
                    }
                }, 280)
            }

            function cancel() {
                reject();
                removeDropdown()
            }

        })
    };

    /*
    * base64转blob对象
    * */
    this.convertBase64UrlToBlob = function (base64) {
        var parts = base64.split(";base64,");
        var contentType = parts[0].split(":")[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;
        var uInt8Array = new Uint8Array(rawLength);
        for (var i = 0; i < rawLength; i++) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
    }

    /*
    * 获取浏览器类型
    * */
    this.myBrowser = function () {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        if (userAgent.indexOf("OPR") > -1) {
            return "Opera";
        } //判断是否Opera浏览器 OPR/43.0.2442.991
        if (userAgent.indexOf("Firefox") > -1) {
            return "FF";
        } //判断是否Firefox浏览器  Firefox/51.0
        if (userAgent.indexOf("Trident") > -1) {
            return "IE";
        } //判断是否IE浏览器  Trident/7.0; rv:11.0
        if (userAgent.indexOf("Edge") > -1) {
            return "Edge";
        } //判断是否Edge浏览器  Edge/14.14393
        if (userAgent.indexOf("Chrome") > -1) {
            return "Chrome";
        } // Chrome/56.0.2924.87
        if (userAgent.indexOf("Safari") > -1) {
            return "Safari";
        }
    }

    this.toChinesNum = function(num){
        //如果数字含有小数部分，那么可以将小数部分单独取出
        //将小数部分的数字转换为字符串的方法：
        //壹贰叁肆伍陆柒捌玖拾
        var chnNumChar = ["零","壹","貳","叁","肆","伍","陸","柒","捌","玖"];
        var chnUnitSection = ["","萬","億","萬億","億億"];
        var chnUnitChar = ["","拾","佰","千"];
        var numToChn = function(num){
            var index =  num.toString().indexOf(".");
            if(index != -1){
                var str = num.toString().slice(index);
                var a = "點";
                for(var i=1;i<str.length;i++){
                    a += chnNumChar[parseInt(str[i])];
                }
                return a ;
            }else{
                return ;
            }
        }
        //定义在每个小节的内部进行转化的方法，其他部分则与小节内部转化方法相同
        function sectionToChinese(section){
            var str = '', chnstr = '',zero= false,count=0;   //zero为是否进行补零， 第一次进行取余由于为个位数，默认不补零
            while(section>0){
                var v = section % 10;  //对数字取余10，得到的数即为个位数
                if(v ==0){                    //如果数字为零，则对字符串进行补零
                    if(zero){
                        zero = false;        //如果遇到连续多次取余都是0，那么只需补一个零即可
                        chnstr = chnNumChar[v] + chnstr;
                    }
                }else{
                    zero = true;           //第一次取余之后，如果再次取余为零，则需要补零
                    str = chnNumChar[v];
                    str += chnUnitChar[count];
                    chnstr = str + chnstr;
                }
                count++;
                section = Math.floor(section/10);
            }
            return chnstr;
        }
        //定义整个数字全部转换的方法，需要依次对数字进行10000为单位的取余，然后分成小节，按小节计算，当每个小节的数不足1000时，则需要进行补零
        function TransformToChinese(num){
            var a = numToChn(num) || '';
            num = Math.floor(num);
            var unitPos = 0;
            var strIns = '', chnStr = '';
            var needZero = false;

            if(num === 0){
                return chnNumChar[0];
            }
            while(num > 0){
                var section = num % 10000;
                if(needZero){
                    chnStr = chnNumChar[0] + chnStr;
                }
                strIns = sectionToChinese(section);
                strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0];
                chnStr = strIns + chnStr;
                needZero = (section < 1000) && (section > 0);
                num = Math.floor(num / 10000);
                unitPos++;
            }
            return chnStr + a;
        }
        return TransformToChinese(num)
    }
    this.toChineseDate = function(str){
        let chinese=['零','一','二','三','四','五','六','七','八','九','十'];
        let numStr=str.replace(/[^0-9]+/g, '');
        let year=chinese[numStr[0]]+chinese[numStr[1]]+chinese[numStr[2]]+chinese[numStr[3]];
        let month=numStr[4]==='0'?chinese[numStr[5]]:chinese[10]+chinese[numStr[5]];
        let day='';
        if (numStr[6] === '0') {
            day = chinese[numStr[7]];
        } else if (numStr[6] === '1') {
            if (numStr[7] === '0') {
                day = chinese[10];
            } else {
                day = chinese[10] + chinese[numStr[7]];
            }
        } else if (numStr[6] === '2' || numStr[6] === '3') {
            if (numStr[7] === '0') {
                day = chinese[numStr[6]] + chinese[10];
            } else {
                day = chinese[numStr[6]] + chinese[10] + chinese[numStr[7]];
            }
        }
        return year+'年'+month+'月'+day+'日';
    }
    this.banEventDefault = function (e) {
        e.preventDefault();
        e.stopPropagation()
    };

    /*
    * 保存图片到本地,仅限pc端
    * */
    this.saveMyImage = function (base64, name) {
        var blob = that.convertBase64UrlToBlob(base64);
        if (that.myBrowser() === "IE") {
            window.navigator.msSaveBlob(blob, name + ".png");
        } else if (that.myBrowser() === "FF") {
            window.location.href = url;
        } else {
            var a = document.createElement("a");
            a.download = URL.createObjectURL(blob);
            a.href = URL.createObjectURL(blob);
            a.click();
        }
    }

    /*
    * 表单校验实例
    * String formName 表单名
    * Array/Object  rules 表单验证规则
    * Object rules[item]  {key:表单项字段;name:表单项名称;required:是否必填;validator:自定义校验方法,返回boolean;message:检验失败提示文本}
    * */
    this.Validate = function (formName, rules) {
        var that = this;
        rules = !!rules ? rules : {};
        this.form = document.getElementsByName(formName)[0];
        //检验单个输入框
        this.valid = function (key,rule) {
            var input = that.form[key];
            if(!rule){
                rules.forEach(function (item) {
                    item['key'] === key ? rule = item : ''
                });
            }
            var valids = true;
            if (rule['required'] === true) {
                if(input.value === '' || input.value === undefined || input.value == null){
                    var message = rule['name'] ? '请输入' + rule['name'] : rule['message'];
                    createMessage(rule['key'], message);
                    return false
                }
            }
            if (rule['validator'] && typeof rule['validator'] === 'function') {
                if(!!input.value && rule['validator'](input.value) === false){
                    var _message = rule['message'] ? rule['message'] : (rule['name'] ? rule['name'] + '格式错误' : '此处不能为空');
                    createMessage(rule['key'],_message);
                    valids = false
                }
            }
            if(valids) removeMessage(rule['key']);
            return valids;
        };
        this.validator = function () {
            return new Promise(function (resolve, reject) {
                var failedValid = [];
                for (var item in rules){
                    if(!that.valid(rules[item]['key'],rules[item])) failedValid.push(rules[item]);
                }
                if (failedValid.length !== 0) {
                    reject()
                }else {
                    resolve()
                }
            })
        };

        function createMessage(key, text) {
            removeMessage(key);
            var message = document.createElement('span');
            var inputContent = document.getElementsByName(key)[0].parentNode;
            message.className = 'validateMessage';
            message.id = 'validate_' + key;
            message.innerText = text;
            inputContent.appendChild(message)
        }

        function removeMessage(key) {
            var inputContent = document.getElementsByName(key)[0].parentNode;
            var message = document.getElementById('validate_' + key);
            if (message) {
                inputContent.removeChild(message)
            }
        }

        return this;
    }
}

var globalFn = new GlobalFn();